package com.example.element.module.media

import android.content.Context
import android.content.Intent
import android.media.MediaPlayer
import android.net.Uri
import com.example.common.base.AbsActivity
import com.example.element.R
import com.example.element.databinding.ActMediaBinding

class MediaActivity :AbsActivity<ActMediaBinding>() {

    private val audioPlayer = MediaPlayer()
    private lateinit var videoUri:Uri

    companion object{
        @JvmStatic
        fun open(context: Context) {
            context.startActivity(Intent(context,MediaActivity::class.java))
        }
    }

    override fun getLayoutId()=R.layout.act_media

    override fun main() {
        initAudioPlayer()
        initVideoPlayer()
    }

    override fun initListener() {

        mBinding.btnStart.setOnClickListener {
            if (!audioPlayer.isPlaying) {
                audioPlayer.start()
            }
        }

        mBinding.btnPause.setOnClickListener {
            if (audioPlayer.isPlaying) {
                audioPlayer.pause()
            }
        }

        mBinding.btnStop.setOnClickListener {
            audioPlayer.reset()
            initAudioPlayer()
        }

        mBinding.btnVideoStart.setOnClickListener {
            if (!mBinding.videoView.isPlaying) {
                mBinding.videoView.start()
            }
        }

        mBinding.btnVideoPause.setOnClickListener {
            if (mBinding.videoView.isPlaying) {
                mBinding.videoView.pause()
            }
        }

        mBinding.btnVideoStop.setOnClickListener {
            if (mBinding.videoView.isPlaying) {
                //重新播放
                mBinding.videoView.resume()
            } else {
                mBinding.videoView.start()
            }
        }
    }

    private fun initAudioPlayer() {
        //获取AssetManager实例
        val assetManager = assets
        //音频文件句柄打开
        val fd = assetManager.openFd("a.mp3")
        //player准备工作
        audioPlayer.setDataSource(fd.fileDescriptor, fd.startOffset, fd.length)
        audioPlayer.prepare()
    }

    private fun initVideoPlayer() {
        //将raw下视频资源解析成Uri对象-Android要求的固定写法
        videoUri = Uri.parse("android.resource://$packageName/${R.raw.media_test}")
        mBinding.videoView.setVideoURI(videoUri)
    }

    override fun onDestroy() {
        super.onDestroy()
        //释放音频资源
        audioPlayer.stop()
        audioPlayer.release()
        //释放视频资源
        mBinding.videoView.suspend()
    }
}